package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.config.WebSocketServer;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 新增报警规则
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    /**
     * 过滤数据
     * @param deviceDataVo
     */
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        //判断当前上报的时间是否超过1分钟
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if(between > 60){
            return;
        }

        //查询所有的该产品下和该物模型下的规则
        List<AlertRule> allAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        //查询该产品下、该设备下、该物模型下的规则
        List<AlertRule> theAllAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        //合并
        Collection<AlertRule> alertRules = CollUtil.addAll(allAlertRules, theAllAlertRules);
        if(CollUtil.isEmpty(alertRules)){
            return;
        }

        alertRules.forEach(rule ->deviceDateAlarmHandler(deviceDataVo,rule));


    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${zzyl.alert.managerRole}")
    private String managerRole;



    /**
     * 过滤数据是否触发报警规则
     * @param deviceDataVo
     * @param rule
     */
    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule rule) {
        //判断上报时间是否在规则的生效时段内   00:00:00~23:59:59
        String[] split = rule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //获取上报时间
        LocalTime time = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();
        //符合条件，不在上报时间内，结束
        if(startTime.isAfter(time) || endTime.isBefore(time)){
            return;
        }

        //获取IotID
        String iotId = deviceDataVo.getIotId();

        //统计次数的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+iotId+":"+deviceDataVo.getFunctionId()+":"+rule.getId();

        //数据对比：上报的数据与规则中的阈值进行对比
        //两个参数：x,y    x==y 返回值0  x > y  返回大于0 的数值   x< y  返回小于0的数值
        int compare = NumberUtil.compare(Double.valueOf(deviceDataVo.getDataValue()), rule.getValue());
        //规则中有操作符  >=  <
        if((rule.getOperator().equals(">=") && compare >= 0) ||
                (rule.getOperator().equals("<") && compare < 0) ){
            log.info("当前设备上报的数据符合规则异常");
        }else {
            //正常的数据
            redisTemplate.delete(aggCountKey);
            return;
        }



        //判断是否有沉默周期数据（redis）
        //前缀+iotID+funcationId+规则ID
        String silentCacheKey = CacheConstants.ALERT_SILENT_PREFIX+iotId+":"+deviceDataVo.getFunctionId()+":"+rule.getId();
        String silentData = redisTemplate.opsForValue().get(silentCacheKey);
        if(StringUtils.isNotEmpty(silentData)){
            return;
        }

        //处理的逻辑，持续周期的内容
        String aggData = redisTemplate.opsForValue().get(aggCountKey);
        int count = StringUtils.isEmpty(aggData)? 1 : Integer.parseInt(aggData) + 1;
        //count是否与持续周期相等  3个持续周期
        if(ObjectUtil.notEqual(count,rule.getDuration())){
            //不相等
            redisTemplate.opsForValue().set(aggCountKey,count+"");
            return;
        }
        //删除redis报警数据
        redisTemplate.delete(aggCountKey);

        //存储报警的沉默周期（设置一个过期时间为：规则中的沉默周期值）
        redisTemplate.opsForValue().set(silentCacheKey,deviceDataVo.getDataValue(),rule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //保存报警数据
        //找到对应的人
        List<Long> customerIs = new ArrayList<>();
        if(rule.getAlertDataType().equals(0)){
            //老人异常数据
            //找老人所关联的护理员
            if(deviceDataVo.getLocationType() == 0){
                customerIs = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if(deviceDataVo.getLocationType() == 1 && deviceDataVo.getPhysicalLocationType() == 2){
                customerIs = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            //设备异常数据-->维修工
            customerIs = userRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
        }

        //别管是哪种情况，都要通知超级管理员
        List<Long> managerIds = userRoleMapper.selectUserIdByRoleName(managerRole);
        List<Long> allIds = CollUtil.addAllIfNotContains(managerIds, customerIs);
        //去重
//        allIds = allIds.stream().distinct().collect(Collectors.toList());
        allIds = CollUtil.distinct(allIds);

        //保存报警数据
        List<AlertData> list = insertAlertData(allIds, rule, deviceDataVo);
        //获取需要通知的人   &&  通知的消息内容是什么
        List<Long> userIds = list.stream().map(AlertData::getUserId).collect(Collectors.toList());

        //websocket推送消息
        websocketNotify(list.get(0),rule,userIds);

    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 报警通知相关负责人
     * @param alertData
     * @param rule
     * @param userIds
     */
    private void websocketNotify(AlertData alertData, AlertRule rule, List<Long> userIds) {
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData,AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(rule.getFunctionName());
        alertNotifyDto.setAlertDataType(rule.getAlertDataType());
        //报警状态
        alertNotifyDto.setNotifyType(1);
        webSocketServer.sendMessageToConsumer(alertNotifyDto,userIds);
    }

    @Autowired
    private AlertDataMapper alertDataMapper;



    /**
     * 保存报警数据
     * @param allIds
     * @param rule
     * @param deviceDataVo
     */
    private List<AlertData> insertAlertData(List<Long> allIds, AlertRule rule, DeviceDataVo deviceDataVo) {
        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);//待处理
        alertData.setType(rule.getAlertDataType());
        //遍历ids
        List<AlertData> list = allIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            return dbAlertData;
        }).collect(Collectors.toList());

        //批量保存
        alertDataMapper.batchInsert(list);
        return list;
    }
}
